package com.smartsofa.main;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.smartsofa.R;
import com.smartsofa.adapter.TopicCommentListAdapter;
import com.smartsofa.entity.Page;
import com.smartsofa.entity.Topic;
import com.smartsofa.entity.User;
import com.smartsofa.util.MyUtils;

public class DetailTopic extends Activity {
	
	
	private LinearLayout lay_topic_comment;
	private ProgressDialog	mDialog_comment;
	private Button bt_back;
	private String url;
	private Boolean flag;	
	private JSONObject json;
	private ProgressDialog mDialog;	
	
	//定义网络连接超时判定变量
	private boolean network_timeout=false;
	private JSONArray jsonarr;
	private List<Map<String, Object>> mData; 
	private List<Map<String, Object>> mData2=new ArrayList<Map<String,Object>>(); 
	private TopicCommentListAdapter adapter;
	private PullToRefreshListView pullToRefresh;  //实现下拉刷新与上拉加载的ListView	
	private Button bt_comment;

	Page page=new Page();
	Topic topic=new Topic();
	
	Dialog dialog;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);			
		setContentView(R.layout.detail_topic);				
		initView();
		Intent intent=getIntent();
		Bundle bundle=intent.getExtras();
		topic.setTopicId(bundle.getInt("topicId"));
		loadData();	
	}
	private void initView(){
		lay_topic_comment=(LinearLayout) findViewById(R.id.lay_topic_comment);
		 //显示加载对话框
	    mDialog = new ProgressDialog(DetailTopic.this);
		mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		mDialog.setMessage("加载中，请稍后...");
		mDialog.show();	
		bt_comment = (Button) findViewById(R.id.img_bt_comment);
		
		//评论监听事件		
		bt_comment.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub

						LayoutInflater inflaterDl = LayoutInflater.from(DetailTopic.this);
				        LinearLayout layout = (LinearLayout)inflaterDl.inflate(R.layout.comment_dialog, null ); 
		                dialog = new Dialog(DetailTopic.this,R.style.FullHeightDialog); 
		                dialog.getWindow().setGravity(Gravity.BOTTOM);
		                dialog.getWindow().setContentView(layout);
//		                requestWindowFeature(Window.FEATURE_NO_TITLE);

						getWindow().setFlags(
								WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
								WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
						/*
				         * 将对话框的大小按屏幕大小的百分比设置
				         */
						dialog.setCancelable(true);
				        WindowManager m = getWindowManager();
				        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用

				        WindowManager.LayoutParams p =  dialog.getWindow().getAttributes(); // 获取对话框当前的参数值

				        p.height = (int) (d.getWidth() * 0.2); // 高度设置为屏幕的0.6

				        p.width = (int) (d.getWidth() * 1); // 宽度设置为屏幕的0.65

				        dialog.getWindow().setAttributes(p);
		                dialog.show();
		                final EditText et_comment=(EditText) layout.findViewById(R.id.et_comment);
		                Button bt_submit_comment= (Button) layout.findViewById(R.id.bt_submit_comment);               
		                bt_submit_comment.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View arg0) {
								// TODO Auto-generated method stub

								String comment=et_comment.getText().toString();
								if(comment.equals("")){
									Toast.makeText(getApplicationContext(), "至少写点什么吧...", Toast.LENGTH_SHORT).show();
								}
								else{
									Thread comment_thread=new Thread(new comment_topic_thread(comment));
									comment_thread.start();
								}						
							}
						});
					}
				});
				
		
		
		bt_back=(Button) findViewById(R.id.back);
		bt_back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				DetailTopic.this.finish();
			}
		});
		 pullToRefresh = (PullToRefreshListView)findViewById(R.id.pullToRefresh);     
	        pullToRefresh.setMode(Mode.BOTH);
	        
	      
	        init(); 
	        pullToRefresh.setOnRefreshListener(new OnRefreshListener2<ListView>(){  
	       	 public void onPullDownToRefresh(  
	                    PullToRefreshBase<ListView> refreshView) {  
	                // TODO Auto-generated method stub                                  
				    new GetDataTaskDown().execute(); 
	            }  
	              
	            public void onPullUpToRefresh(  
	                    PullToRefreshBase<ListView> refreshView) {  
	                // TODO Auto-generated method stub  
	           	 new GetDataTaskUp().execute();           	   
	            }
	       });				
	}
	
	private void loadData(){			
		Thread contentdata = new Thread(new loadDataNet());
		contentdata.start();
	}
	class loadDataNet implements Runnable{
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {		
				url=MyUtils.getUrl()+"topic_getCommentList?topicid="+topic.getTopicId();
				Log.i("DetailTopic url:", url);
				HttpGet request = new HttpGet(url);																
				BasicHttpParams httpParams = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParams,MyUtils.REQUEST_TIMEOUT);
			    HttpClient httpClient = new DefaultHttpClient(httpParams);
	            HttpResponse httpResponse = httpClient.execute(request);							       
		       	
		      if (httpResponse.getStatusLine().getStatusCode() == 200) {
		    	network_timeout=true;
		        String jsonString = EntityUtils.toString(httpResponse.getEntity());
		        json = new JSONObject(jsonString);
		        flag=(Boolean) json.get("success");			        				      		       
		      }
		      }catch (Exception e) {
		        	 e.printStackTrace();
		      }
			Message msg = content_handler.obtainMessage();
			if(network_timeout){
				if (flag) {				
					msg.what = 1;									
				}else{
					msg.what = 2;			
				}
			}			
			else{
				msg.what = 3;						
			}
			content_handler.sendMessage(msg);
		}
		
	}
	Handler content_handler = new Handler() {
		public void handleMessage(Message msg) {	
			mDialog.cancel();
			switch (msg.what) {		
			case 1:	
				
				try {
					page.setCurrpage(1);
					JSONObject jsonobj=json.getJSONObject("obj");
					final JSONObject topicobj;
					topicobj=jsonobj.getJSONObject("topic");
					
					if(jsonobj.has("commentlist")&&jsonobj.getJSONArray("commentlist")!=null){
						mData=getData(jsonobj);
					    adapter = new TopicCommentListAdapter(DetailTopic.this.getApplicationContext(),mData, topicobj);
					    adapter.setTopic(topic);
				        pullToRefresh.setAdapter(adapter);			        
				    }else{					
				    	adapter = new TopicCommentListAdapter(DetailTopic.this.getApplicationContext(),mData, topicobj);
				    	adapter.setTopic(topic);
				        pullToRefresh.setAdapter(adapter);
				    }
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				break;
			case 2:
				Toast.makeText(DetailTopic.this, "数据加载失败，请稍后重试！", Toast.LENGTH_SHORT).show();
				break;
			case 3:
				Toast.makeText(DetailTopic.this, "网络连接超时！", Toast.LENGTH_SHORT).show();
				break;
			}
		}		
	};
	/**
	 * 获取数据
	 * @throws JSONException 
	 */
	private List<Map<String, Object>> getData(JSONObject json) throws JSONException{		
		jsonarr=json.getJSONArray("commentlist");
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	    for(int i=0;i<jsonarr.length();i++)  
           {  			    	   
               HashMap<String, Object> map = new HashMap<String, Object>();  
               if(jsonarr.getJSONObject(i).has("userImg")){
            	   map.put("userImg", jsonarr.getJSONObject(i).get("userImg"));
               }			   
			   map.put("userName", jsonarr.getJSONObject(i).get("userName")); 
               map.put("comment", jsonarr.getJSONObject(i).get("comment"));
               map.put("commentTime", jsonarr.getJSONObject(i).get("commentTime"));
               map.put("floorNum", jsonarr.getJSONObject(i).get("floorNum"));
               list.add(map);
           }
	    return list;
	}
	private void init(){    
        ILoadingLayout startLabels = pullToRefresh    
                .getLoadingLayoutProxy(true, false);    
        startLabels.setPullLabel("下拉刷新...");// 刚下拉时，显示的提示    
        startLabels.setRefreshingLabel("正在载入...");// 刷新时    
        startLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示    
    
        ILoadingLayout endLabels = pullToRefresh.getLoadingLayoutProxy(    
                false, true);    
        endLabels.setPullLabel("上拉刷新...");// 刚下拉时，显示的提示    
        endLabels.setRefreshingLabel("正在载入...");// 刷新时    
        endLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示    
    }
	
	   private class GetDataTaskDown extends AsyncTask<Void, Void, Void> {  
		   
	       //后台处理部分  
	       protected Void doInBackground(Void... params) {  
	           // Simulates a background job.  
	    	   loadData(); 
	           return null;
	       }
	 
	       //这里是对刷新的响应，可以利用addFirst（）和addLast()函数将新加的内容加到LISTView中  
	       //根据AsyncTask的原理，onPostExecute里的result的值就是doInBackground()的返回值  
	       protected void onPostExecute(Void result) {  
	           //在头部增加新添内容  
//	           mListItems.addFirst(result);  	             
	           //通知程序数据集已经改变，如果不做通知，那么将不会刷新mListItems的集合  
	           adapter.notifyDataSetChanged();  
	           // Call onRefreshComplete when the list has been refreshed.  
	           pullToRefresh.onRefreshComplete();  	 
	           super.onPostExecute(result);  
	       }
	   }
	   
	   private class GetDataTaskUp extends AsyncTask<Void, Void, List<Map<String, Object>>> {  
		   
	       //后台处理部分  
	       protected List<Map<String, Object>> doInBackground(Void... params) {  
	           // Simulates a background job.  
	    	   try {
					url=MyUtils.getUrl()+"topic_getCommentList?topicid="+topic.getTopicId()+"&currpage="+page.getCurrpage()+"&pagesize="+page.getPagesize();
					HttpGet request = new HttpGet(url);																
					BasicHttpParams httpParams = new BasicHttpParams();
					HttpConnectionParams.setConnectionTimeout(httpParams,MyUtils.REQUEST_TIMEOUT);
				    HttpClient httpClient = new DefaultHttpClient(httpParams);
		            HttpResponse httpResponse = httpClient.execute(request);							       
			       	
			      if (httpResponse.getStatusLine().getStatusCode() == 200) {
			    	network_timeout=true;
			        String jsonString = EntityUtils.toString(httpResponse.getEntity());
			        json = new JSONObject(jsonString);
			        flag=(Boolean) json.get("success");
			        Message msg = pulltorefresh_handler.obtainMessage();
					if(network_timeout){
						mData2.clear();
						if (flag) {				
							
							page.setCurrpage(page.getCurrpage());
							JSONObject jsonobj=new JSONObject();
							jsonobj=json.getJSONObject("obj");					
							if(jsonobj.isNull("commentlist")){
								Log.i("commentmessagenull", "true");
								msg.what = 2;
							}else{
								msg.what = 1;
							mData2=getData(jsonobj);
							}
							
						}
					}			
					else{
						msg.what = 3;						
					}
					pulltorefresh_handler.sendMessage(msg);
					}			      
			      }catch (Exception e) {
			        	 e.printStackTrace();
			      }								
	           return mData2;
	       }
	 
	       //这里是对刷新的响应，可以利用addFirst（）和addLast()函数将新加的内容加到LISTView中  
	       //根据AsyncTask的原理，onPostExecute里的result的值就是doInBackground()的返回值  
	       protected void onPostExecute(List<Map<String, Object>> result) {  
	    	   if(mData2.size()>0){
	    		   //在头部增加新添内容  
		           mData.addAll(result);  
		           //通知程序数据集已经改变，如果不做通知，那么将不会刷新mListItems的集合  
		           adapter.notifyDataSetChanged();  
		           // Call onRefreshComplete when the list has been refreshed.  		           
	    	   }
	    	   pullToRefresh.onRefreshComplete();
	           super.onPostExecute(result);  
	       }
	   }
	   
	   
		Handler pulltorefresh_handler = new Handler() {
			public void handleMessage(Message msg) {			
				switch (msg.what) {		
				case 1:						
					if(mData2.size()==0){
						Toast.makeText(DetailTopic.this, "没有更多数据了！", Toast.LENGTH_SHORT).show();
					}
					break;
				case 2:
					Log.i("hello", "hi");
				
					Toast.makeText(getApplication(), "没有更多数据了！", Toast.LENGTH_SHORT).show();
				
					break;
				case 3:
					Toast.makeText(DetailTopic.this, "网络连接超时！", Toast.LENGTH_SHORT).show();
					break;
				}
			}		
		};
		/**
		 * 评论线程
		 */
		class comment_topic_thread implements Runnable{

			private String str_comment;
			public comment_topic_thread(String comment){
				this.str_comment=comment;
			}
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {		
					User user=new User();
				url = MyUtils.getUrl() + "topic_commentTopic?topicid="
						+ topic.getTopicId() + "&userid=" + MyUtils.getUSERID()
						+ "&comment=" + str_comment;
				Log.i("url", url);
					HttpGet request = new HttpGet(url);		
					//以下三行为连接服务器超时判断，如果超时将不执行以下所有代码
				   BasicHttpParams httpParams = new BasicHttpParams();
				   HttpConnectionParams.setConnectionTimeout(httpParams,MyUtils.REQUEST_TIMEOUT);
			       HttpClient httpClient = new DefaultHttpClient(httpParams);
			       HttpResponse httpResponse = httpClient.execute(request);							       
			       	
			      if (httpResponse.getStatusLine().getStatusCode() == 200) {
			    	network_timeout=true;
			        String jsonString = EntityUtils.toString(httpResponse.getEntity());
			        json = new JSONObject(jsonString);
			        flag=(Boolean) json.get("success");			        				      		       
			      }
			      }catch (Exception e) {
			        	 e.printStackTrace();
			      }
				Message msg = comment_handler.obtainMessage();
				if(network_timeout){
					if (flag) {				
						msg.what = 1;									
					}else{
						msg.what = 2;			
					}
				}			
				else{
					msg.what = 3;						
				}
				comment_handler.sendMessage(msg);
			}			
		}
		Handler comment_handler = new Handler() {
			public void handleMessage(Message msg) {
				
				switch (msg.what) {		
				case 1:
					Toast.makeText(DetailTopic.this, "评论成功！", Toast.LENGTH_SHORT).show();	
					dialog.dismiss();
					loadData();
					break;
				case 2:
					Toast.makeText(DetailTopic.this, "操作失败，请稍后再试！", Toast.LENGTH_SHORT).show();
					break;
				case 3:
					Toast.makeText(DetailTopic.this, "网络连接超时！", Toast.LENGTH_SHORT).show();
					break;
				}
			}
		};

		
		
}
